package com.boyinet.data.export.repoistory;

import com.boyinet.data.export.domain.DataHistory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lengchunyun
 */
@Repository
public interface DataHistoryRepository extends CrudRepository<DataHistory, Long>, JpaSpecificationExecutor<DataHistory> {

    /**
     * 根据日期和传感器no获取当前值
     *
     * @param no   传感器序号
     * @param date 日期
     * @return Histories
     */
    List<DataHistory> findHistoriesByEquipmentIdEqualsAndGmtCreateEquals(String no, Long date);

    /**
     * 时间区间及SN分页获取历史数据
     *
     * @param no       sn
     * @param start    起始日期
     * @param end      结束日期
     * @param pageable 分页参数
     * @return List<DataHistory>
     */
    default Page<DataHistory> pageDataHistoriesByEquipmentIdEqualsAndGmtCreateBetween(String no, Date start, Date end,
                                                                                      Pageable pageable) {
        return this.findAll((Specification<DataHistory>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<Predicate>();
            list.add(criteriaBuilder.equal(root.get("equipmentId").as(String.class), no));
            list.add(criteriaBuilder.between(root.get("gmtCreate").as(Long.class), start.getTime(), end.getTime()));
            return criteriaBuilder.and(list.toArray(new Predicate[]{}));
        }, pageable);
    }

    List<DataHistory> findDataHistoriesByEquipmentIdEqualsAndGmtCreateBetween(String no, Long start, Long end);

    /**
     * 根据时间获取所有当前时间下的历史数据
     *
     * @param time 时间
     * @return 历史数据
     */
    List<DataHistory> findHistoriesByGmtCreateEquals(Long time);


    /**
     * 计算数据总数
     *
     * @param no    sn
     * @param start 起始日期
     * @param end   结束日期
     * @return 数据总数
     */
    Long countByEquipmentIdEqualsAndGmtCreateBetween(String no, Long start, Long end);
   
}
